//
//  NSObject+Extension.swift
//  DouYuZB
//
//  Created by DSDL on 2016/10/26.
//  Copyright © 2016年 鼎商动力. All rights reserved.
//

import UIKit
extension UIView {
    /**
     主要用于获取 Cell 的 Nib 对象，用于 registerNib
     */
    class func NibObject() -> UINib {
        let hasNib: Bool = Bundle.main.path(forResource: self.nameOfClass, ofType: "nib") != nil
        guard hasNib else {
            assert(!hasNib, "Invalid parameter") // assert
            return UINib()
        }
        return UINib(nibName: self.nameOfClass, bundle:nil)
    }
    //主要用于获取 UIView 的 Nib 对象，用于 View加在xib
    class func fromNib<T : UIView>(nibName: String? = nil) -> T {
        let v: T? = fromNib(nibNameOrNil: nibName)
        return v!
    }
   private class func fromNib<T : UIView>(nibNameOrNil: String? = nil) -> T? {
        var view: T?
        let name: String
        if let nibName = nibNameOrNil {
            name = nibName
        } else {
            // Most nibs are demangled by practice, if not, just declare string explicitly
            name = "\(T.self)".components(separatedBy: ".").last!
        }
        let nibViews = Bundle.main.loadNibNamed(name, owner: nil, options: nil)
        for v in nibViews! {
            if let tog = v as? T {
                view = tog
            }
        }
        return view
    }
}
extension NSObject {
    class var nameOfClass: String {
        return NSStringFromClass(self).components(separatedBy: ".").last! as String
    }
    //用于获取 cell 的 reuse identifier
    class var identifier: String {
        return String(format: "%@_identifier", self.nameOfClass)
    }
}
